package com.shiftl.ui.aroma;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.shiftl.data.aroma.dto.DTOFactory;
import com.shiftl.data.aroma.model.Incense;
import com.shiftl.service.incense.client.IncenseAdminService;
import com.shiftl.service.incense.client.IncenseAdminServiceAsync;

public class IncenseEditPanel extends VerticalPanel {

	private static final String KEY = "Key";

	private static final String COUNTRY = "country";

	private static final String COMPANY = "company";

	private static final String DESCRIPTION = "description";

	private static final String NAME = "name";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final IncenseAdminServiceAsync incenseService = GWT.create(IncenseAdminService.class);

	private final String[] dataEntryFieldNames = { KEY, NAME, DESCRIPTION, COMPANY, COUNTRY };
	private OneButtonDialog resultDialog;

	private TableWithTitles incenseData;
	private Button saveButton;
	private Map<String, Widget> dataEntryFields;

	/**
	 * This is the entry point method.
	 */
	public IncenseEditPanel() {

		incenseData = new TableWithTitles(dataEntryFieldNames);
		// build data entry fields

		dataEntryFields = new HashMap<String, Widget>();
		for (int col = 1; col < dataEntryFieldNames.length; col++) {
			dataEntryFields.put(dataEntryFieldNames[col], new TextBox());
		}

		incenseData.fillRowWithWidgetMap(dataEntryFields, 1);
		add(incenseData);

		saveButton = new Button("Save");
		saveButton.addStyleName("saveButton");
		final IncenseTableHandler handler = new IncenseTableHandler();
		saveButton.addClickHandler(handler);
		add(saveButton);

		resultDialog = new OneButtonDialog("Result", "Close", "Displaying Dialog");
		resultDialog.getButton().addClickHandler(new ClickHandler() {
			public void onClick(final ClickEvent event) {
				resultDialog.hide();
				saveButton.setEnabled(true);
				// saveButton.setFocus(true);
			}
		});

		TextBox tmpTxt = (TextBox) dataEntryFields.get(dataEntryFieldNames[1]);
		tmpTxt.setFocus(true);
	}

	// Create a handler for the saveButton and nameField
	class IncenseTableHandler implements ClickHandler, KeyUpHandler {
		/**
		 * Fired when the user clicks on the saveButton.
		 */
		String savedId;
		Map<String, String> lastEditedValues;
		int currentRow;

		public void onClick(final ClickEvent event) {
			// get values from the last row
			currentRow = -1;
			lastEditedValues = null;
			savedId = null;

			currentRow = incenseData.getRowCount() - 1;
			lastEditedValues = incenseData.getValues(currentRow);
			final Incense inc = DTOFactory.newIncense(lastEditedValues.get(NAME), lastEditedValues.get(DESCRIPTION));
			inc.setMaker(lastEditedValues.get(COMPANY));
			inc.setOrigin(lastEditedValues.get(COUNTRY));
			saveIncense(inc);

		}

		/**
		 * Fired when the user types in the nameField.
		 */
		public void onKeyUp(final KeyUpEvent event) {
			if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {

			}
		}

		/**
		 * Send the name from the nameField to the server and wait for a response.
		 */
		private void saveIncense(final Incense inc) {

			incenseService.saveIncense(inc, new AsyncCallback<String>() {
				public void onFailure(final Throwable caught) {
					resultDialog.setText("Failure");
					resultDialog.getHtmlLabel().setHTML("Failed: " + caught.getLocalizedMessage());
					resultDialog.getButton().setFocus(true);
					resultDialog.center();
				}

				public void onSuccess(final String result) {
					savedId = result;
					lastEditedValues.put(KEY, savedId);
					incenseData.fillRowWithTextMap(lastEditedValues, currentRow);
					incenseData.fillRowWithWidgetMap(dataEntryFields, currentRow + 1);
					TextBox tmpTxt = (TextBox) dataEntryFields.get(dataEntryFieldNames[1]);
					tmpTxt.setFocus(true);
					for (String fieldName : dataEntryFieldNames) {
						tmpTxt = (TextBox) dataEntryFields.get(fieldName);
						if (tmpTxt != null) {
							tmpTxt.setText("");
						}
					}

				}
			});
		}
	}
}
